<template>
	<main class="main-page" id="">
		<template v-if="showHeader">
			<section class="page-section mb-3">
				<div class="container-fluid">
					<div class="grid justify-content-between align-items-center">
						<div class="col ">
							<div class=" text-2xl text-primary font-bold">
								{{ $t('studentgradesummary') }}
							</div>
						</div>
						<div class="col-fixed flex gap-2">
							<template v-if="auth.canView('studentgradesummary/add')">
								<router-link :to="`/studentgradesummary/add`">
									<Button :label="$t('addNewStudentgradesummary')" icon="pi pi-plus" type="button"
										class="p-button bg-primary" />
								</router-link>
							</template>
							<template v-if="auth.canView('studentgradesummary/batch-generate-reports')">
								<Button :label="$t('batchGenerateReports')" icon="pi pi-file-pdf" type="button"
									class="p-button bg-green-600" @click="batchGenerateReports" />
							</template>
							<template v-if="auth.canView('studentgradesummary/report-hashes')">
								<Button label="批量签名" icon="pi pi-pencil" type="button" class="p-button bg-blue-600"
									@click="batchSignReports" />
							</template>
							<template v-if="auth.canView('studentgradesummary/batch-reports')">
								<Button label="批量上传到区块链" icon="pi pi-cloud-upload" type="button"
									class="p-button bg-purple-600" @click="batchUploadToContract" />
							</template>
						</div>
						<div class="col-12 md:col-3 ">
							<span class="p-input-icon-left w-full">
								<i class="pi pi-search" />
								<InputText :placeholder="$t('search')" class="w-full" :value="filters.search.value"
									@input="debounce(() => { filters.search.value = $event.target.value })" />
							</span>
						</div>

					</div>
				</div>
			</section>
		</template>
		<section class="page-section ">
			<div class="container-fluid">
				<div class="grid ">
					<div class="col comp-grid">
						<div class="flex align-items-center">
							<filter-tags :controller="page.filterController" />
						</div>
						<div>
							<template v-if="showBreadcrumbs && $route.query.tag && !isSubPage">
								<Breadcrumb :home="{ icon: 'pi pi-home', to: '/studentgradesummary' }"
									:model="pageBreadCrumb" />
							</template>
							<!-- page records template -->
							<div class="page-records">
								<div v-if="pageReady && !records.length"
									class="p-3 my-3 text-500 text-lg font-medium text-center">
									{{ $t('noRecordFound') }}
								</div>

								<div class="grid" v-else>
									<div class="col-12 md:col-6 lg:col-4" v-for="data in records"
										:key="data.summary_id">
										<Card class="mb-3">
											<template #header>
												<div class="flex justify-content-between align-items-center p-3">
													<span class="font-bold">学期: {{ data.semester_name }}</span>
													<SplitButton dropdownIcon="pi pi-bars"
														class="p-button dropdown-only p-button-text p-button-plain"
														:model="getActionMenuModel(data)">
														<i></i>
													</SplitButton>
												</div>
											</template>
											<template #content>
												<div class="grid">
													<div class="col-6">
														<div class="text-sm text-500">学生ID</div>
														<div class="flex align-items-center mt-2">
															<Button class="p-button-text p-0" icon="pi pi-eye"
																label="用户详情" v-if="data.student_id"
																@click="app.openPageDialog({ page: 'users/view', url: `/users/view/${data.student_id}`, closeBtn: true })" />
														</div>
													</div>
													<div class="col-6">
														<div class="text-sm text-500">摘要ID</div>
														<div class="mt-2">
															<router-link
																:to="`/studentgradesummary/view/${data.summary_id}`">
																{{ data.summary_id }}
															</router-link>
														</div>
													</div>
													<div class="col-6 mt-3">
														<div class="text-sm text-500">数据哈希</div>
														<div class="flex align-items-center gap-2 mt-2">
															<span class="font-mono text-sm truncate">
																{{ data.data_hash ? truncateHash(data.data_hash) : '未生成'
																}}
															</span>
															<Button v-if="data.data_hash" icon="pi pi-copy"
																class="p-button-text p-button-sm" v-tooltip="'复制哈希'"
																@click="copyHash(data.data_hash)" />
														</div>
													</div>
													<div class="col-6 mt-3">
														<div class="text-sm text-500">CID</div>
														<div class="flex align-items-center gap-2 mt-2">
															<span class="font-mono text-sm truncate">
																{{ data.cid ? truncateHash(data.cid) : '未上传IPFS' }}
															</span>
															<Button v-if="data.cid" icon="pi pi-copy"
																class="p-button-text p-button-sm" v-tooltip="'复制哈希'"
																@click="copyHash(data.cid)" />
															<Button v-if="data.cid" icon="pi pi-external-link"
																class="p-button-text p-button-sm" v-tooltip="'在IPFS中查看'"
																@click="openIPFS(data.cid)" />
														</div>
													</div>
													<div class="col-6 mt-3">
														<div class="text-sm text-500">交易哈希</div>
														<div class="flex align-items-center gap-2 mt-2">
															<span class="font-mono text-sm truncate">
																{{
																	data.transaction_hash ?
																		truncateHash(data.transaction_hash) : '未上链'
																}}
															</span>
															<Button v-if="data.transaction_hash" icon="pi pi-copy"
																class="p-button-text p-button-sm" v-tooltip="'复制哈希'"
																@click="copyHash(data.transaction_hash)" />
														</div>
													</div>
													<div class="col-6 mt-3">
														<div class="text-sm text-500">教务签名</div>
														<div class="flex align-items-center gap-2 mt-2">
															<span class="font-mono text-sm truncate">
																{{
																	data.registrar_sig ?
																		truncateHash(data.registrar_sig) : '未签名'
																}}
															</span>
															<Button v-if="data.registrar_sig" icon="pi pi-copy"
																class="p-button-text p-button-sm" v-tooltip="'复制哈希'"
																@click="copyHash(data.registrar_sig)" />
															<Button v-if="data.registrar_sig" icon="pi pi-check"
																class="p-button-text p-button-sm" v-tooltip="'验证签名'"
																@click="verifyRegistrarSignature(data)" />
														</div>
													</div>
													<div class="col-6 mt-3">
														<div class="text-sm text-500">学生签名</div>
														<div class="flex align-items-center gap-2 mt-2">
															<span class="font-mono text-sm truncate">
																{{
																	data.student_sig ?
																		truncateHash(data.student_sig) : '未签名'
																}}
															</span>
															<Button v-if="data.registrar_sig" icon="pi pi-copy"
																class="p-button-text p-button-sm" v-tooltip="'复制哈希'"
																@click="copyHash(data.student_sig)" />
														</div>
													</div>
													<div class="col-12 mt-3">
														<div class="text-sm text-500">PDF报表</div>
														<div class="mt-2">
															<PDFViewer v-if="data.pdf_path" :src="data.pdf_path"
																width="100%" height="160px" />
															<span v-else>-</span>
														</div>
													</div>
													<div class="col-4 mt-3">
														<div class="text-sm text-500">pdf报表生成状态</div>
														<div class="mt-2">
															<Tag :value="getProcessingStatusText(data.processing_status)"
																:severity="getProcessingStatusSeverity(data.processing_status)" />
														</div>
													</div>
													<div class="col-4 mt-3" v-if="data.onchain_status">
														<div class="text-sm text-500">区块链状态</div>
														<div class="mt-2">
															<Tag :value="getOnchainStatusText(data.onchain_status)"
																:severity="getOnchainStatusSeverity(data.onchain_status)" />
														</div>
													</div>
													<div class="col-4 mt-3">
														<div class="text-sm text-500">学生确认状态</div>
														<div class="mt-2">
															<Tag :value="getConfirmStatusText(data.confirm_status)"
																:severity="getConfirmStatusSeverity(data.confirm_status)" />
														</div>
													</div>
												</div>
											</template>
										</Card>
									</div>
								</div>
							</div>
							<!-- end of empty record-->
							<!-- pagination component-->
							<template v-if="showFooter && pageReady">
								<div class="grid justify-content-between align-items-center">
									<div class="flex gap-2 flex-grow-0">
										<template v-if="auth.canView('studentgradesummary')">
											<div v-if="selectedItems.length" class="m-2">
												<Button @click="deleteItem(selectedItems)" icon="pi pi-trash"
													class="p-button-danger" :title="$t('deleteSelected')" />
											</div>
										</template>
									</div>
									<div v-if="paginate && totalPages > 1" class="flex-grow-1">
										<Paginator class="paginator-flat my-3" :first="recordsPosition - 1"
											@page="(event) => { pagination.page = event.page + 1 }"
											:rows="pagination.limit" :totalRecords="totalRecords">
											<template #start>
												<span class="px-2">
													{{ $t('records') }} <b>{{ recordsPosition }} {{ $t('of') }} {{
														totalRecords }}</b>
												</span>
											</template>
											<template #end>
											</template>
										</Paginator>
									</div>
								</div>
							</template>
							<!-- end of pagination component-->
						</div>
					</div>
				</div>
			</div>
		</section>

		<!-- 添加验证成绩弹框 -->
		<Dialog v-model:visible="showVerifyDialog" :style="{ width: '50vw' }" header="验证成绩报告" :modal="true">
			<div class="grid">
				<div class="col-12">
					<div class="text-lg font-bold mb-3">成绩报告信息</div>
					<div class="grid">
						<div class="col-6">
							<div class="text-sm text-500">学期</div>
							<div class="font-medium">{{ verifyData.semester_name }}</div>
						</div>
						<div class="col-6">
							<div class="text-sm text-500">CID</div>
							<div class="font-mono text-sm truncate">{{ verifyData.cid }}</div>
						</div>
						<div class="col-12 mt-3">
							<div class="text-sm text-500">教务签名</div>
							<div class="font-mono text-sm truncate">{{ verifyData.registrar_sig || '未签名' }}</div>
						</div>
						<div class="col-12 mt-3">
							<div class="text-sm text-500">学生签名</div>
							<div class="font-mono text-sm truncate">{{ verifyData.student_sig || '未签名' }}</div>
						</div>
					</div>
				</div>
			</div>
			<template #footer>
				<Button label="取消" icon="pi pi-times" @click="showVerifyDialog = false" class="p-button-text" />
				<Button label="确认验证" icon="pi pi-check" @click="confirmVerification" :loading="verifying" />
			</template>
		</Dialog>

		<!-- 添加验证教务签名对话框 -->
		<Dialog v-model:visible="showRegistrarVerifyDialog" :style="{ width: '50vw' }" 
			:header="$t('verifyRegistrarSignature')" :modal="true">
			<div class="verify-content">
				<div class="verify-item">
					<label>学生地址：</label>
					<span>{{ selectedRecord?.student_address }}</span>
				</div>
				<div class="verify-item">
					<label>学期：</label>
					<span>{{ selectedRecord?.semester_name }}</span>
				</div>
				<div class="verify-item">
					<label>CID：</label>
					<span>{{ selectedRecord?.cid }}</span>
				</div>
				<div class="verify-item">
					<label>教务签名：</label>
					<span class="font-mono text-sm truncate">
						{{ selectedRecord?.registrar_sig ? truncateHash(selectedRecord.registrar_sig) : '无签名' }}
					</span>
				</div>
			</div>
			<template #footer>
				<Button :label="$t('cancel')" icon="pi pi-times" @click="showRegistrarVerifyDialog = false"
					class="p-button-text" />
				<Button :label="$t('verify')" icon="pi pi-check" @click="confirmRegistrarVerify" :loading="verifyingRegistrar" />
			</template>
		</Dialog>
	</main>
</template>
<script setup>
import { toRefs, onMounted, ref } from 'vue';
import { usePageStore } from 'src/store/page';
import { useApp } from 'src/composables/app.js';
import { useAuth } from 'src/composables/auth';
import { $t } from 'src/services/i18n';
import { useListPage } from 'src/composables/listpage.js';
import { ApiService } from '@/services/api';
// 确保导入web3Service的方法
import { getAccounts, signMessageHash,getContractInstance} from '@/services/web3Service';

const props = defineProps({
	primaryKey: {
		type: String,
		default: 'summary_id',
	},
	pageStoreKey: {
		type: String,
		default: 'STUDENTGRADESUMMARY',
	},
	pageName: {
		type: String,
		default: 'studentgradesummary',
	},
	routeName: {
		type: String,
		default: 'studentgradesummarylist',
	},
	apiPath: {
		type: String,
		default: 'studentgradesummary/index',
	},
	autoLoad: {
		type: Boolean,
		default: true,
	},
	enableCache: {
		type: Boolean,
		default: false,
	},
	paginate: {
		type: Boolean,
		default: true,
	},
	showHeader: {
		type: Boolean,
		default: true,
	},
	showFooter: {
		type: Boolean,
		default: true,
	},
	showBreadcrumbs: {
		type: Boolean,
		default: true,
	},
	exportButton: {
		type: Boolean,
		default: true,
	},
	importButton: {
		type: Boolean,
		default: false,
	},
	multiCheckbox: {
		type: Boolean,
		default: true,
	},
	page: {
		type: Number,
		default: 1,
	},
	limit: {
		type: Number,
		default: 6,
	},
	mergeRecords: { // for infinite loading
		type: Boolean,
		default: false,
	},
	search: {
		type: String,
		default: '',
	},
	fieldName: null,
	fieldValue: null,
	queryParams: {
		type: Object,
		default: () => ({})
	},
	sortBy: {
		type: String,
		default: '',
	},
	sortType: {
		type: String,
		default: 'desc', //desc or asc
	},
	isSubPage: {
		type: Boolean,
		default: false,
	},
	emptyRecordMsg: {
		type: String,
		default: () => $t('noRecordFound'),
	},
	titleBeforeDelete: {
		type: String,
		default: $t('deleteRecord'),
	},
	msgBeforeDelete: {
		type: String,
		default: () => $t('promptDeleteRecord'),
	},
	msgAfterDelete: {
		type: String,
		default: () => $t('recordDeletedSuccessfully'),
	},
	filterTagClass: {
		type: String,
		default: 'surface-card p-2 text-500 flex-grow-1 text-center m-1 mb-3 flex-grow-1 text-center',
	}
});

const app = useApp();
const auth = useAuth();

const defaultStoreState = {
	filters: {
		search: {
			tag: "Search",
			value: '',
			valueType: 'single',
			options: [],
		}
	},
	pagination: {
		page: props.page,
		limit: props.limit,
		sortBy: props.sortBy,
		sortType: props.sortType
	},
	primaryKey: props.primaryKey,
	enableCache: props.enableCache
}
const store = usePageStore(props.pageStoreKey, defaultStoreState);

// page hooks where logics resides
const page = useListPage({ store, props });

const { records, filters, totalRecords, selectedItems, pagination, } = toRefs(store.state);
const { pageReady, loading, } = toRefs(page.state);

const { pageBreadCrumb, totalPages, recordsPosition, } = page.computedProps;

const { load, exportPage, debounce, onSort, deleteItem, } = page.methods;

// 添加验证相关的响应式变量
const showVerifyDialog = ref(false);
const verifyData = ref({});
const verifying = ref(false);

// 添加验证教务签名相关的响应式变量
const showRegistrarVerifyDialog = ref(false);
const selectedRecord = ref(null);
const verifyingRegistrar = ref(false);

function getActionMenuModel(data) {
	return [
		{
			label: () => $t('view'),
			to: `/studentgradesummary/view/${data.summary_id}`,
			icon: "pi pi-eye",
			visible: auth.canView('studentgradesummary/view')
		},
		{
			label: () => $t('edit'),
			to: `/studentgradesummary/edit/${data.summary_id}`,
			icon: "pi pi-pencil",
			visible: auth.canView('studentgradesummary/edit')
		},
		{
			label: () => $t('delete'),
			command: (event) => { deleteItem(data.summary_id) },
			icon: "pi pi-trash",
			visible: auth.canView('studentgradesummary/delete')
		},
		{
			label: '确认成绩',
			icon: 'pi pi-check',
			visible: auth.canView('studentgradesummary/update-confirm-status') && 
					data.confirm_status !== 'confirmed' &&
					data.processing_status === 'completed',
			command: () => confirmGradeReport(data)
		}
	]
}

onMounted(() => {
	const pageTitle = $t('studentgradesummary');
	app.setPageTitle(props.routeName, pageTitle);
});

// 修改 batchGenerateReports 方法
async function batchGenerateReports() {
	try {
		const semester = prompt('请输入学期名称 (例如: 2023-2024学年第一学期)');
		if (!semester) return;

		const confirmed = confirm(`确定要为所有学生生成 ${semester} 的成绩报表吗？`);
		if (!confirmed) return;

		loading.value = true;
		const response = await ApiService.post('/studentgradesummary/batch-generate-reports', {
			semester_name: semester
		});

		app.flashMsg('任务已提交', '成绩报表正在后台生成，请稍后查看状态', 'info');

		// 启动轮询检查任务状态
		const pollInterval = setInterval(async () => {
			try {
				const { data } = await ApiService.get(`/studentgradesummary/index`, {
					params: {
						filters: {
							semester_name: semester
						}
					}
				});

				const allCompleted = data.records.every(record =>
					record.processing_status === 'completed' ||
					record.processing_status === 'failed'
				);

				if (allCompleted) {
					clearInterval(pollInterval);
					load(); // 刷新列表
					app.flashMsg('任务完成', `${semester} 的成绩报表生成完成`, 'success');
				}
			} catch (error) {
				console.error('轮询出错:', error);
				clearInterval(pollInterval);
			}
		}, 5000); // 每5秒检查一次

	} catch (error) {
		console.error('批量生成出错:', error);
		app.flashMsg('批量生成出错', error.response?.data?.message || '请求失败', 'error');
	} finally {
		loading.value = false;
	}
}

// 在卡片内容中添加状态显示


// 添加状态文本和样式映射方法
function getProcessingStatusText(status) {
	const statusMap = {
		'pending': '等待中',
		'processing': '处理中',
		'completed': '已完成',
		'failed': '失败'
	};
	return statusMap[status] || status;
}

function getProcessingStatusSeverity(status) {
	const severityMap = {
		'pending': 'info',
		'processing': 'warning',
		'completed': 'success',
		'failed': 'danger'
	};
	return severityMap[status] || 'info';
}

// 哈希截断显示
const truncateHash = (hash) => {
	if (!hash) return '';
	return `${hash.substring(0, 8)}...${hash.substring(hash.length - 6)}`;
};

// 复制功能
const copyHash = async (hash) => {
	try {
		await navigator.clipboard.writeText(hash);
		app.flashMsg('复制', '复制成功', 'success');
	} catch (e) {
		app.flashMsg('复制', '复制失败', 'error');
	}
};

function getOnchainStatusText(status) {
	const statusMap = {
		'not_on_chain': '未上链',
		'pending': '处理中',
		'confirmed': '已确认'
	};
	return statusMap[status] || status;
}

function getOnchainStatusSeverity(status) {
	const severityMap = {
		'not_on_chain': 'danger',
		'pending': 'warning',
		'confirmed': 'success'
	};
	return severityMap[status] || 'info';
}

function getConfirmStatusText(status) {
    const statusMap = {
        'not_confirm': '未确认',
        'confirming': '确认中',
        'confirmed': '已确认'
    };
    return statusMap[status] || status;
}

function getConfirmStatusSeverity(status) {
    const severityMap = {
        'not_confirm': 'danger',
        'confirming': 'warning',
        'confirmed': 'success'
    };
    return severityMap[status] || 'info';
}

// 在script部分添加新方法
async function batchSignReports() {
	try {
		loading.value = true;

		// 1. 获取所有需要签名的报告哈希
		const { data: reportHashes } = await ApiService.get('/studentgradesummary/report-hashes');

		// 2. 获取当前账户
		const accounts = await getAccounts();
		const currentAccount = accounts[0];

		// 3. 对每个报告进行签名
		const signatures = {};
		for (const [summaryId, signHash] of Object.entries(reportHashes)) {
			try {
				if (!signHash) continue;

				// 签名数据哈希
				const signature = await signMessageHash(signHash, currentAccount);
				signatures[summaryId] = signature;

				// 保存签名到后端
				await ApiService.post('/studentgradesummary/save-registrar-signature', {
					summary_id: summaryId,
					signature
				});

				app.flashMsg('签名成功', `报告 ${summaryId} 签名已保存`, 'success');
			} catch (err) {
				console.error(`报告 ${summaryId} 签名失败:`, err);
				app.flashMsg('签名失败', `报告 ${summaryId} 签名失败: ${err.message}`, 'error');
			}
		}

		// 4. 刷新列表数据
		await load();
		app.flashMsg('批量签名完成', `已完成 ${Object.keys(signatures).length} 个报告的签名`, 'success');
	} catch (error) {
		console.error('批量签名出错:', error);
		app.flashMsg('批量签名出错', error.response?.data?.message || '请求失败', 'error');
	} finally {
		loading.value = false;
	}
}


// 在methods中添加批量上传方法
async function batchUploadToContract() {
    try {
        loading.value = true;

        // 1. 获取批量报告数据
        const response = await ApiService.get('/studentgradesummary/batch-reports');
        const batchReports = response.data;

        if (!batchReports.length) {
            app.flashMsg('上传失败', '没有可上传的报告数据', 'error');
            return;
        }

        // 2. 获取当前账户
        const accounts = await getAccounts();
        const currentAccount = accounts[0];

        // 3. 获取合约实例
        const contract = await getContractInstance('GradeLogicV1');

        // 4. 逐个上传批次
        for (const batch of batchReports) {
            try {
                // 转换数据结构为合约需要的格式
                const reportsInput = batch.reports.map(report => ({
                    student: report.student,
                    semester: report.semester,
                    cid: report.cid,
                    registrarSig: report.registrarSig || "0x"
                }));

                // 生成批量签名
                const batchSig = await signMessageHash(batch.messageToSign, currentAccount);

				console.log(JSON.stringify(reportsInput))
				console.log(batchSig)
                // 调用合约方法
                const tx = await contract.methods.batchPublishReports(
                    reportsInput,
                    batchSig
                ).send({
                    from: currentAccount,
                    gas: 5000000 // 设置足够的gas
                });

                // 更新后端状态
                await ApiService.post('/studentgradesummary/update-batch-onchain-status', {
                    batchHash: batch.batchHash,
                    transactionHash: tx.transactionHash
                });

                app.flashMsg('上传成功', `批次 ${batch.batchHash} 已成功上传到区块链`, 'success');

				await load();
            } catch (err) {
                console.error(`批次上传失败:`, err);
                app.flashMsg('上传失败', `批次上传失败: ${err.message}`, 'error');
            }
        }
    } catch (error) {
        console.error('批量上传出错:', error);
        app.flashMsg('批量上传出错', error.message || '请求失败', 'error');
    } finally {
        loading.value = false;
    }
}




async function confirmGradeReport(record) {
    try {
        // 显示验证弹框
        verifyData.value = {
			summary_id: record.summary_id,
            semester_name: record.semester_name,
            cid: record.cid,
            registrar_sig: record.registrar_sig,
            student_sig: record.student_sig
        };
        showVerifyDialog.value = true;
    } catch (error) {
        console.error('显示验证弹框出错:', error);
        app.flashMsg('错误', '显示验证信息失败', 'error');
    }
}

// 添加确认验证方法
async function confirmVerification() {
    try {
        verifying.value = true;
        
        // 1. 获取签名哈希
        const { data: hashData } = await ApiService.get(`/studentgradesummary/student-confirm-hash/${verifyData.value.summary_id}`);
        
        // 2. 获取当前账户
        const accounts = await getAccounts();
        const currentAccount = accounts[0];
        
        // 3. 签名哈希
        const signature = await signMessageHash(hashData.hash, currentAccount);
        
        // 4. 调用合约确认
        const contract = await getContractInstance('GradeLogicV1');
        await contract.methods.confirmReport(
            verifyData.value.semester_name,
            verifyData.value.cid,
            signature
        ).send({ from: currentAccount });
        
        // 5. 更新后端状态
        await ApiService.post(`/studentgradesummary/update-confirm-status/${verifyData.value.summary_id}`, {
            confirm_status: 'confirmed',
            student_sig: signature
        });
        
        // 关闭弹框并显示成功消息
        showVerifyDialog.value = false;
        app.flashMsg('确认成功', '成绩确认成功', 'success');
        await load(); // 刷新列表
    } catch (error) {
        console.error('确认成绩出错:', error);
        app.flashMsg('确认失败', error.message || '成绩确认失败', 'error');
    } finally {
        verifying.value = false;
    }
}

// 在script部分添加openIPFS方法
const openIPFS = (cid) => {
    const ipfsUrl = `https://ipfs.io/ipfs/${cid}`;
    window.open(ipfsUrl, '_blank');
};

// 添加验证教务签名方法
const verifyRegistrarSignature = async (record) => {
    selectedRecord.value = record;
    showRegistrarVerifyDialog.value = true;
};

// 添加确认验证教务签名方法
const confirmRegistrarVerify = async () => {
    try {
        verifyingRegistrar.value = true;
        const response = await ApiService.post('studentgradesummary/verify-registrar-signature', {
            summary_id: selectedRecord.value.summary_id,
            signature: selectedRecord.value.registrar_sig
        });

        const result = response.data;

        if (result.success) {
            app.flashMsg('验证成功', `签名验证通过，教务: ${result.registrarName} (ID: ${result.registrarId})`, 'success');
        } else {
            app.flashMsg('验证失败', result.message || '签名验证失败', 'error');
        }
    } catch (error) {
        console.error('验证教务签名时出错:', error);
        app.flashMsg('错误', '验证教务签名时发生错误', 'error');
    } finally {
        showRegistrarVerifyDialog.value = false;
        verifyingRegistrar.value = false;
    }
};

</script>
<style scoped>
.verify-content {
    padding: 1rem;
}

.verify-item {
    display: flex;
    margin-bottom: 1rem;
    padding: 0.5rem;
    border-bottom: 1px solid var(--surface-border);
}

.verify-item label {
    font-weight: 600;
    min-width: 100px;
    color: var(--text-color-secondary);
}

.verify-item span {
    flex: 1;
}
</style>


